//
//  JSThemeManager.m
//  JSBasicFramework
//
//  Created by Apple on 2018/8/2.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "JSThemeManager.h"

NSString *const JSThemeChangedNotification = @"JSThemeChangedNotification";
NSString *const JSThemeBeforeChangedName = @"JSThemeBeforeChangedName";
NSString *const JSThemeAfterChangedName = @"JSThemeAfterChangedName";

@implementation JSThemeManager

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static JSThemeManager *instance = nil;
    dispatch_once(&onceToken,^{
        instance = [[super allocWithZone:NULL] init];
    });
    return instance;
}

+ (id)allocWithZone:(struct _NSZone *)zone{
    return [self sharedInstance];
}

- (instancetype)init {
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleThemeChangedNotification:) name:JSThemeChangedNotification object:nil];
    }
    return self;
}
- (void)handleThemeChangedNotification:(NSNotification *)notification {
    NSObject<JSThemeProtocol> *themeBeforeChanged = notification.userInfo[JSThemeBeforeChangedName];
    themeBeforeChanged = [themeBeforeChanged isKindOfClass:[NSNull class]] ? nil : themeBeforeChanged;
    
    NSObject<JSThemeProtocol> *themeAfterChanged = notification.userInfo[JSThemeAfterChangedName];
    themeAfterChanged = [themeAfterChanged isKindOfClass:[NSNull class]] ? nil : themeAfterChanged;
    
    [self themeBeforeChanged:themeBeforeChanged afterChanged:themeAfterChanged];
}
- (void)setCurrentTheme:(NSObject<JSThemeProtocol> *)currentTheme {
    BOOL isThemeChanged = _currentTheme != currentTheme;
    NSObject<JSThemeProtocol> *themeBeforeChanged = nil;
    if (isThemeChanged) {
        themeBeforeChanged = _currentTheme;
    }
    _currentTheme = currentTheme;
    if (isThemeChanged && themeBeforeChanged) {// 从 nil 变成某个 theme 就不发通知了，初始化时会自动 apply，这里只需要处理在 QD 里手动更改 theme 的场景就行
        [currentTheme applyConfigurationTemplate];
        [[NSNotificationCenter defaultCenter] postNotificationName:JSThemeChangedNotification object:self userInfo:@{JSThemeBeforeChangedName: themeBeforeChanged ?: [NSNull null], JSThemeAfterChangedName: currentTheme ?: [NSNull null]}];
    }
}
#pragma mark - <QDChangingThemeDelegate>

- (void)themeBeforeChanged:(NSObject<JSThemeProtocol> *)themeBeforeChanged afterChanged:(NSObject<JSThemeProtocol> *)themeAfterChanged {
    // 主题发生变化，在这里更新全局 UI 控件的 appearance
//    [QDCommonUI renderGlobalAppearances];
    
    [JSUIHelpr customMoreOperationAppearance];
    [JSUIHelpr customAlertControllerAppearance];
    [JSUIHelpr customDialogViewControllerAppearance];
    [JSUIHelpr customImagePickerAppearance];
    [JSUIHelpr customEmotionViewAppearance];
    // 更新表情 icon 的颜色
    [JSUIHelpr updateEmotionImages];
}
@end
